package com.gzwanchuang.lszg.module.machines;

/**
 * 文件名 : EarningDetailActivity
 * 创建者 : MangoWang
 * 创建日期 : 2019/11/28 20:06
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.gzwanchuang.lszg.R;
import com.gzwanchuang.lszg.adapter.AllowSnAdapter;
import com.gzwanchuang.lszg.base.BaseActivity;
import com.gzwanchuang.lszg.dialog.RecycleViewDialog;
import com.gzwanchuang.lszg.dialog.ShowSelectDialog;
import com.gzwanchuang.lszg.net.Apis;
import com.gzwanchuang.lszg.net.NetworkManager;
import com.gzwanchuang.lszg.net.interfaces.OnRequestCallBack;
import com.gzwanchuang.lszg.proto.Mystock;
import com.gzwanchuang.lszg.utils.StatusBarUtil;
import com.gzwanchuang.lszg.utils.ValidateUtils;
import com.google.protobuf.InvalidProtocolBufferException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import kale.ui.view.dialog.EasyDialog;

public class AllowSnActivity extends BaseActivity {

    Unbinder unbinder;
    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.btn_hua)
    Button btnHua;


    private AllowSnAdapter mAdapter;
    private List<AllowSnListBean> datas = new ArrayList<>();
    private int total;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_allow_sn);
        unbinder = ButterKnife.bind(this);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#ffffff"), true);
        tvTitle.setText("选择SN号");
        initRecyclerView();
        initData();

    }

    private void initData() {
        Mystock.showProductSNCode.Builder builder = Mystock.showProductSNCode.newBuilder();
        builder.setGoodsId(getIntent().getStringExtra("goods_id"));
        if (ValidateUtils.isValidate(getIntent().getStringExtra("member_id"))) {
            builder.setMemberId(getIntent().getStringExtra("member_id"));
        }
        NetworkManager.INSTANCE.post(Apis.showProductSNCode, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                List<Mystock.showProductSNCode.array> lianBean = Mystock.showProductSNCode.parseFrom(response).getArrayListList();
                List<Mystock.showProductSNCode.List> NolianBean = Mystock.showProductSNCode.parseFrom(response).getOtherListList();
                // 1.遍历连号的列表
                for (int i = 0; i < lianBean.size(); i++) {
                    AllowSnListBean snListBean = new AllowSnListBean();
                    Mystock.showProductSNCode.array array = lianBean.get(i);
                    List<Mystock.showProductSNCode.List> tempList = array.getListList();
                    if (tempList.size() == 1) {
                        snListBean.setShowSnNumber(tempList.get(0).getSnCode());
                    } else {
                        snListBean.setShowSnNumber(tempList.get(0).getSnCode() + "--" + tempList.get(tempList.size() - 1).getSnCode());
                    }
                    snListBean.setTotalSnNumber(String.valueOf(tempList.size()));
                    // 获取有多少个可以给用划拨
                    int canUser = 0;
                    for (int j = 0; j < tempList.size(); j++) {
                        AllowSnListBean.SnMessage snMessage = new AllowSnListBean.SnMessage();
                        snMessage.setId(tempList.get(j).getId());
                        snMessage.setSn_code(tempList.get(j).getSnCode());
                        snMessage.setIs_transfer(tempList.get(j).getIsTransfer());
                        if (tempList.get(j).getIsTransfer().equals("0")) canUser++;
                        snListBean.getSnList().add(snMessage);
                    }
                    snListBean.setUseSnNumber(String.valueOf(canUser));
                    datas.add(snListBean);
                }
                // 2.遍历不连号的列表
                if (ValidateUtils.isValidate(NolianBean)) {
                    AllowSnListBean snListBean = new AllowSnListBean();
                    snListBean.setShowSnNumber("不连号机具");
                    snListBean.setTotalSnNumber(String.valueOf(NolianBean.size()));
                    // 获取有多少个可以给用划拨
                    int canUser = 0;
                    for (int i = 0; i < NolianBean.size(); i++) {
                        AllowSnListBean.SnMessage snMessage = new AllowSnListBean.SnMessage();
                        snMessage.setId(NolianBean.get(i).getId());
                        snMessage.setSn_code(NolianBean.get(i).getSnCode());
                        snMessage.setIs_transfer(NolianBean.get(i).getIsTransfer());
                        if (NolianBean.get(i).getIsTransfer().equals("0")) canUser++;
                        snListBean.getSnList().add(snMessage);
                    }
                    snListBean.setUseSnNumber(String.valueOf(canUser));
                    datas.add(snListBean);
                }
                mAdapter.setNewInstance(datas);
                mAdapter.notifyDataSetChanged();

            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    private void initRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(mAdapter = new AllowSnAdapter(mContext, datas));

        mAdapter.setEmptyView(R.layout.recycle_empty);
        // 每个item的点击事件
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            ShowSelectDialog.Builder builder = new ShowSelectDialog.Builder(mContext);
            builder.setOnDialogClickListener((v, type) -> {
                RecycleViewDialog.Builder builder2 = new RecycleViewDialog.Builder(mContext);
                builder2.setData(datas.get(position));
                builder2.setType(type);
                builder2.setOnDismissListener(dialog ->
                {
                    mAdapter.notifyItemChanged(position);
                    total = 0;
                    for (int i = 0; i < datas.size(); i++) {
                        total = total + datas.get(i).getSelectedSnList().size();
                    }
                    if (total == 0) {
                        btnHua.setText("确定");
                    } else {
                        btnHua.setText("确定(共选" + total + "台)");
                    }
                });
                EasyDialog build2 = builder2.build();
                build2.setCancelable(false);
                build2.show(getSupportFragmentManager());
            });
            EasyDialog build = builder.build();
            build.setCancelable(true);
            build.show(getSupportFragmentManager());
        });


    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @OnClick({R.id.back_iv, R.id.btn_hua})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.btn_hua:
                if (total == 0) {
                    showToast("请先选择划拨SN");
                } else {
                    StringBuilder buffer = new StringBuilder();
                    StringBuilder buffer2 = new StringBuilder();
                    buffer2.append("\n");
                    for (int i = 0; i < datas.size(); i++) {
                        for (int j = 0; j < datas.get(i).getSelectedSnList().size(); j++) {
                            buffer.append(datas.get(i).getSelectedSnList().get(j).getSn_code()).append(",");
                        }
                        if (datas.get(i).getSelectedSnList().size() != 0) {
                            buffer2.append(datas.get(i).getShowSnNumber()).append("\n").append("已选").append(datas.get(i).getSelectedSnList().size()).append("台/共").append(datas.get(i).getTotalSnNumber()).append("台").append("\n");
                        }
                    }
                    String sn_up_code = buffer.substring(0, buffer.length() - 1);
                    String sn_code = buffer2.toString();
                    Intent intent = new Intent();
                    Log.e("sn_up_code", sn_up_code);
                    Log.e("sn_code", sn_code);
                    intent.putExtra("sn_code", sn_code);
                    intent.putExtra("sn_up_code", sn_up_code);
                    intent.putExtra("sn_number", String.valueOf(total));
                    setResult(400, intent);
                    finish();
                }
                break;
        }
    }
}
